<!--
 * @Description: 
 * @version: 
 * @Author: 尹鹏孝
 * @Date: 2022-01-12 15:48:28
 * @LastEditors: 尹鹏孝
 * @LastEditTime: 2022-01-12 16:31:37
-->
<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>树形扁平化和逆扁平化</title>
</head>

<body>
    <script>
        let data = [];
        for (let i = 1; i <= 1000; i++) {
            let obj = {
                id: i,
                name: `name-${i}`,
                pid: i - 1 == 0 ? '' : i - 1
            }
            data.push(obj);
        }

        function treeData(arr, child = 'children') {
            //此方法必须是数组按照正序排序后才可用，如果是乱序需要排好顺序，否则会报错
            let result = [];
            if (Array.isArray(arr) && arr.length) {
                let ctrArr = JSON.parse(JSON.stringify(arr));
                ctrArr = ctrArr.sort((a, b) => {
                    return a.id - b.id
                });
                let middle = {};
                ctrArr.forEach(el => {
                    middle[el.id] = el;
                    el[child] = [];
                    if (el.pid === '') {
                        result.push(el);
                    } else {
                        middle[el.pid][child].push(el);

                    }
                })
            }

            return result;
        }

        let myTestData = treeData(data);
        console.log(myTestData);


        //将树形数据
        /*这种结构：pid-id是父子关系的对应
        [{
             id: 1,
             pid: '',
             name: 'name-1',
             children: [{
                 id: 2,
                 pid: i,
                 name: 'name-2',
                 children: [{
                     id: 3,
                     pid: 2,
                     name: 'name-3'
                 }]
             }]
         }]
         */
        var platATree = function (arr, children = 'children') {
            let result = [];
            if (Array.isArray(arr) && arr.length) {
                let ctrArr = JSON.parse(JSON.stringify(arr));
                while (ctrArr.length) {
                    let shift = ctrArr.shift();
                    let child = shift[children];
                    //把当前元素的子元素数组删除
                    delete shift[children];
                    result.push(shift);
                    if (child) {
                        child.forEach(item => {
                            ctrArr.push(item)
                        })
                    }
                }
            }
            return result;

        }

        let myPlatArr = platATree(myTestData);
        console.log(myPlatArr);


    </script>

</body>

</html>